package io.github.talelin.latticy.controller.v1;

import io.github.talelin.latticy.service.AIImageGenerationService;
import io.github.talelin.latticy.service.OSSUploadService;
import io.github.talelin.latticy.vo.UnifyResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * AI图片生成控制器
 */
@RestController
@RequestMapping("/v1/ai-image")
@CrossOrigin(origins = "*")
@Slf4j
public class AIImageController {

    @Autowired
    private AIImageGenerationService aiImageGenerationService;

    @Autowired
    private OSSUploadService ossUploadService;

    /**
     * 生成图片
     * @param request 生成请求
     * @return 生成结果
     */
    @PostMapping("/generate")
    public Map<String, Object> generateImage(@RequestBody ImageGenerationRequest request) {
        try {
            log.info("收到图片生成请求: {}", request);

            // 生成图片
            AIImageGenerationService.AIImageResult result = aiImageGenerationService.generateImage(
                    request.getPrompt(),
                    request.getModel(),
                    request.getSize(),
                    request.getGuidanceScale(),
                    request.getWatermark()
            );

            if (!result.isSuccess()) {
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("error", "图片生成失败: " + result.getErrorMessage());
                errorData.put("success", false);
                return errorData;
            }

            // 上传到OSS
            String ossUrl = null;
            if (result.getUrl() != null) {
                try {
                    ossUrl = ossUploadService.uploadImageFromUrl(
                            result.getUrl(), 
                            "ai-generated/", 
                            "generated_" + System.currentTimeMillis() + ".jpg"
                    );
                    log.info("图片上传到OSS成功: {}", ossUrl);
                } catch (Exception e) {
                    log.error("图片上传到OSS失败", e);
                    // 即使上传失败，也返回原始URL
                }
            }

            // 构建响应
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("originalUrl", result.getUrl());
            responseData.put("ossUrl", ossUrl);
            responseData.put("revisedPrompt", result.getRevisedPrompt());
            responseData.put("success", true);

            return responseData;

        } catch (Exception e) {
            log.error("图片生成失败", e);
            Map<String, Object> errorData = new HashMap<>();
            errorData.put("error", "图片生成失败: " + e.getMessage());
            errorData.put("success", false);
            return errorData;
        }
    }

    /**
     * 生成商品图片
     * @param request 商品图片生成请求
     * @return 生成结果
     */
    @PostMapping("/generate-product")
    public UnifyResponseVO<Map<String, Object>> generateProductImage(@RequestBody ProductImageRequest request) {
        try {
            log.info("收到商品图片生成请求: {}", request);

            // 生成商品图片
            AIImageGenerationService.AIImageResult result = aiImageGenerationService.generateProductImage(
                    request.getProductName(),
                    request.getProductType(),
                    request.getStyle()
            );

            if (!result.isSuccess()) {
                UnifyResponseVO<Map<String, Object>> errorResponse = new UnifyResponseVO<>();
                errorResponse.setCode(500);
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("error", "商品图片生成失败: " + result.getErrorMessage());
                errorResponse.setMessage(errorData);
                return errorResponse;
            }

            // 上传到OSS
            String ossUrl = null;
            if (result.getUrl() != null) {
                try {
                    ossUrl = ossUploadService.uploadAIGeneratedImage(result.getUrl(), request.getProductName());
                    log.info("商品图片上传到OSS成功: {}", ossUrl);
                } catch (Exception e) {
                    log.error("商品图片上传到OSS失败", e);
                }
            }

            // 构建响应
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("originalUrl", result.getUrl());
            responseData.put("ossUrl", ossUrl);
            responseData.put("revisedPrompt", result.getRevisedPrompt());
            responseData.put("productName", request.getProductName());
            responseData.put("success", true);

            UnifyResponseVO<Map<String, Object>> successResponse = new UnifyResponseVO<>();
            successResponse.setCode(0);
            successResponse.setMessage(responseData);
            return successResponse;

        } catch (Exception e) {
            log.error("商品图片生成失败", e);
            UnifyResponseVO<Map<String, Object>> errorResponse = new UnifyResponseVO<>();
            errorResponse.setCode(500);
            Map<String, Object> errorData = new HashMap<>();
            errorData.put("error", "商品图片生成失败: " + e.getMessage());
            errorResponse.setMessage(errorData);
            return errorResponse;
        }
    }

    /**
     * 生成用户头像
     * @param request 头像生成请求
     * @return 生成结果
     */
    @PostMapping("/generate-avatar")
    public UnifyResponseVO<Map<String, Object>> generateAvatar(@RequestBody AvatarRequest request) {
        try {
            log.info("收到头像生成请求: {}", request);

            // 生成头像
            AIImageGenerationService.AIImageResult result = aiImageGenerationService.generateAvatar(
                    request.getDescription(),
                    request.getStyle()
            );

            if (!result.isSuccess()) {
                UnifyResponseVO<Map<String, Object>> errorResponse = new UnifyResponseVO<>();
                errorResponse.setCode(500);
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("error", "头像生成失败: " + result.getErrorMessage());
                errorResponse.setMessage(errorData);
                return errorResponse;
            }

            // 上传到OSS
            String ossUrl = null;
            if (result.getUrl() != null) {
                try {
                    ossUrl = ossUploadService.uploadUserAvatar(result.getUrl(), request.getUserId());
                    log.info("头像上传到OSS成功: {}", ossUrl);
                } catch (Exception e) {
                    log.error("头像上传到OSS失败", e);
                }
            }

            // 构建响应
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("originalUrl", result.getUrl());
            responseData.put("ossUrl", ossUrl);
            responseData.put("revisedPrompt", result.getRevisedPrompt());
            responseData.put("userId", request.getUserId());
            responseData.put("success", true);

            UnifyResponseVO<Map<String, Object>> successResponse = new UnifyResponseVO<>();
            successResponse.setCode(0);
            successResponse.setMessage(responseData);
            return successResponse;

        } catch (Exception e) {
            log.error("头像生成失败", e);
            UnifyResponseVO<Map<String, Object>> errorResponse = new UnifyResponseVO<>();
            errorResponse.setCode(500);
            Map<String, Object> errorData = new HashMap<>();
            errorData.put("error", "头像生成失败: " + e.getMessage());
            errorResponse.setMessage(errorData);
            return errorResponse;
        }
    }

    /**
     * 图片生成请求
     */
    public static class ImageGenerationRequest {
        private String prompt;
        private String model;
        private String size;
        private Integer guidanceScale;
        private Boolean watermark;

        // Getters and Setters
        public String getPrompt() { return prompt; }
        public void setPrompt(String prompt) { this.prompt = prompt; }
        public String getModel() { return model; }
        public void setModel(String model) { this.model = model; }
        public String getSize() { return size; }
        public void setSize(String size) { this.size = size; }
        public Integer getGuidanceScale() { return guidanceScale; }
        public void setGuidanceScale(Integer guidanceScale) { this.guidanceScale = guidanceScale; }
        public Boolean getWatermark() { return watermark; }
        public void setWatermark(Boolean watermark) { this.watermark = watermark; }
    }

    /**
     * 商品图片生成请求
     */
    public static class ProductImageRequest {
        private String productName;
        private String productType;
        private String style;

        // Getters and Setters
        public String getProductName() { return productName; }
        public void setProductName(String productName) { this.productName = productName; }
        public String getProductType() { return productType; }
        public void setProductType(String productType) { this.productType = productType; }
        public String getStyle() { return style; }
        public void setStyle(String style) { this.style = style; }
    }

    /**
     * 头像生成请求
     */
    public static class AvatarRequest {
        private String description;
        private String style;
        private Long userId;

        // Getters and Setters
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getStyle() { return style; }
        public void setStyle(String style) { this.style = style; }
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
    }
}
